<template>
  <view
    v-if="hasSource"
    ref="videoRef"
    class="video-js vjs-default-skin"
    preload="auto"
    autoplay
    muted
  ></view>
</template>

<script setup>
import { ref, computed, watch, onBeforeUnmount, onMounted } from 'vue';

const props = defineProps({
  sources: {
    type: Array,
    default: () => []
  }
});

const videoRef = ref();
const player = ref();

const hasSource = computed(() => props.sources.length);

// 初始化视频组件
function initVideo() {
  // 没有视频源
  if (player.value) return player.value.dispose();
  // 初始化设置
  player.value = uni.videojs(videoRef.value.$el, {
    preload: 'auto', // 预加载
    autoplay: true, // 自动播放
    controls: true, // 交互控件
    muted: true, // 音频静音
    sources: props.sources // 视频源
  });
  // 加载完毕后播放
  player.value.ready(function() {
    console.log(player);
  });
  
  player.value.on('ended', function() {
    player.value.dispose();
  });
}

// 监控视频源
watch(hasSource, () => initVideo());

onMounted(()=>{
  console.log(videoRef);
  console.log(videoRef.value.$el);
  initVideo()
})

// 组件销毁
onBeforeUnmount(() => {
  if (player.value) return player.value.dispose();
});
</script>

<style lang="scss">
.video-js {
  width: 300px;
  height: 300px;
}
</style>
